package com.ejlchina.tool.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.adolf.androiddemo.databinding.ItemFirmwareUpgradeDialogBinding
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.constant.DEVICE_MODE_ONLINE
import com.ejlchina.tool.constant.SP_DEVICE_MODE
import com.ejlchina.tool.singleton.GlobalConnectObject
import com.ejlchina.tool.singleton.GlobalParams
import com.ejlchina.tool.singleton.SharedPreferenceUtil

class FirmwareUpgradeDialogAdapter(private val dataList: MutableList<BleDeviceBean>): RecyclerView.Adapter<FirmwareUpgradeDialogAdapter.FirmwareUpgradeDialogViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FirmwareUpgradeDialogViewHolder {
        val binding = ItemFirmwareUpgradeDialogBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        return FirmwareUpgradeDialogViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: FirmwareUpgradeDialogViewHolder, position: Int) {
        holder.bindData(dataList[position],position)
    }

    inner class FirmwareUpgradeDialogViewHolder(private val binding: ItemFirmwareUpgradeDialogBinding): RecyclerView.ViewHolder(binding.root){
        @SuppressLint("SetTextI18n")
        fun bindData(firmwareUpgradeDialogBean: BleDeviceBean, position: Int){
            val deviceIndex = if (SharedPreferenceUtil.getInt(SP_DEVICE_MODE) == DEVICE_MODE_ONLINE) {
                "${GlobalParams.getDeviceFromMac(firmwareUpgradeDialogBean.bleDevice.mac)?.bucketNo ?: ""}#  ${firmwareUpgradeDialogBean.bleDevice.mac}"
            } else {
                "${firmwareUpgradeDialogBean.indexInOffline}# ${firmwareUpgradeDialogBean.bleDevice.mac}"
            }


            binding.tvDeviceIndex.text = deviceIndex
            binding.tvDeviceInfo.text = "${firmwareUpgradeDialogBean.version} -> ${firmwareUpgradeDialogBean.upgradeToVersion}"
            handleUpgradeResult(firmwareUpgradeDialogBean.upgradeResult)
            binding.progressBar.setProgress(firmwareUpgradeDialogBean.upgradeResult.toInt(),true)
        }

        @SuppressLint("SetTextI18n")
        private fun handleUpgradeResult(result: Float){
//            Log.i(LOG_TAG, "完成进度---$result")
            if (result < 0f){
                binding.tvUpgradeResult.setTextColor(Color.parseColor("#FF3B30"))
                binding.tvUpgradeResult.text = "失败"
            } else if (result >= 0f && result < 100f){
                binding.tvUpgradeResult.setTextColor(Color.parseColor("#1F39FF"))
                binding.tvUpgradeResult.text = "${result}%"
            } else {
                binding.tvUpgradeResult.setTextColor(Color.parseColor("#1F39FF"))
                binding.tvUpgradeResult.text = "成功"
            }
        }
    }
}